<template>
  <n-card v-if="loading" :bordered="false" class="proCard">
    <n-spin :show="loading"></n-spin>
  </n-card>

  <div v-else :class="[isElectron ? '' : 'no-drop']">
    <div :class="['productionCenter-home', isElectron ? '' : 'disable-click']">
      <TopView
        ref="topViewRef"
        :choose-item="chooseItem"
        :is-adjuest="isAdjuest"
        :isAutoSuccessWork="isAutoSuccessWork"
        :isAutoChangeOrder="isAutoChangeOrder"
        :order-list="orderList"
        :canAutoSuccessWork="canAutoSuccessWork"
        :distributionByOrderCode="distributionByOrderCode"
        :machine="machine"
        :shiftData="shiftData"
        :isElectron="isElectron"
        @update-order-status-fn="updateOrderStatusFn"
        @autoChangeOrderFn="autoChangeOrderFn"
        @load-order-fn="loadOrderFn"
        @setCenterViewValFn="setCenterViewValFn"
        @loadWsOrderFn="loadWsOrderFn"
      />

      <CenterView
        ref="centerViewRef"
        :choose-item="chooseItem"
        :machine="machine"
        :shiftData="shiftData"
        :isElectron="isElectron"
        :btnOptions="btnOptions"
        :adjustingSetting="adjustingSetting"
        :is-adjuest="isAdjuest"
        @setImgListFn="setImgListFn"
        @updateShutdownTimeFn="updateShutdownTimeFn"
      />

      <BottomView
        ref="bottomViewRef"
        :order-list="orderList"
        :choose-item="chooseItem"
        :is-adjuest="isAdjuest"
        :printing-template-ref="printingTemplateRef"
        :isAutoChangeOrder="isAutoChangeOrder"
        @load-order-fn="loadOrderFn"
        @change-choose-item-fn="changeChooseItemFn"
        @update-order-status-fn="updateOrderStatusFn"
        @set-pro-search-val-fn="setProSearchValFn"
        @update-adjuest-order-fn="updateAdjuestOrderFn"
        @open-page-list-dialog-fn="openPageListDialogFn"
        @close-page-list-dialog-fn="closePageListDialogFn"
        @open-adjustment-order-dialog-fn="openAdjustmentOrderDialogFn"
        @checkOrderInfoFn="checkOrderInfoFn"
      />

      <DrawerTemplate ref="drawerTemplateRef" class="drawerTemplate-style" />

      <DrawerTemplateModal
        ref="drawerTemplateModalRef"
        @open-drawer-template-modal-fn="openDrawerTemplateModalFn"
      />

      <PrintingTemplate ref="printingTemplateRef" :label-print-top="labelPrintTop" />

      <DFPageList v-if="showPage" ref="dfPageListRef" :page-options="pageOptions" />

      <AdjustmentOrderDialog
        ref="adjustmentOrderDialogRef"
        :order-list="orderList"
        @load-order-fn="loadOrderFn"
      />

      <UnitOptionsDialog
        ref="unitOptionsDialogRef"
        :machine="machine"
        :imgList="imgList"
        :parameter-unit-list="parameterUnitList"
        :choose-item="chooseItem"
        @distributionFn="distributionFn"
        @getParameterUnitByMaterialVersionFn="getParameterUnitByMaterialVersionFn"
      />

      <CheckOrderInfo
        ref="checkOrderInfoRef"
        :isOpenUnitOptions="isOpenUnitOptions"
        @computedDistributeParameterFn="computedDistributeParameterFn"
        @getParameterUnitListFn="getParameterUnitListFn"
      />

      <AlarmDialog ref="alarmDialog" :alarmList="alarmList" :alarmTypeList="alarmTypeList" />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { defaultPrintTemplate } from '@render/api/system/labelTemplate';
  import TopView from './TopView.vue';
  import CenterView from './CenterView.vue';
  import BottomView from './BottomView.vue';
  import PrintingTemplate from './PrintingTemplate.vue';
  import DrawerTemplate from './Drawer/DrawerTemplate.vue';
  import DrawerTemplateModal from './Drawer/DrawerTemplateModal.vue';
  import {
    getOrderByMachineCode,
    updateAdjuestOrder,
    updateOrder,
    getStatisticsByShiftTime,
  } from '@/api/production/order';
  import { useMixins } from '@/hooks/useMixins';
  import { dateFn } from '@/utils/http/axios/ipcIndex';
  import { usePlcWithOut } from '@/store/modules/plc';
  import { listInfoParamConfigList } from '@/api/system/paramConfig';
  import AdjustmentOrderDialog from './AdjustmentOrderDialog.vue';
  import UnitOptionsDialog from './UnitOptionsDialog.vue';
  import CheckOrderInfo from './CheckOrderInfo.vue';
  import {
    getParameterByMaterialVersion,
    getParameterUnitByMaterialVersion,
    saveParameterByMaterialVersion,
  } from '@render/api/base/material';
  import { handleDistributeFn } from '../handleDistribute';
  import { storage } from '@/utils/Storage';
  import { useWsStore } from '@/store/modules/ws';
  import { LOAD_ORDER_LIST } from '@render/utils/socket/event-type';
  import { infoMachineAdjustment } from '@render/api/gather/machineAdjustment';
  import { listInterfaceImage } from '@render/api/gather/interfaceImage';
  import AlarmDialog from './AlarmDialog.vue';
  import { useProjectSettingStore } from '@/store/modules/projectSetting';
  import { v4 as uuidv4 } from 'uuid';
  import { msToTime } from '@render/utils/dateUtil';

  const projectStore = useProjectSettingStore();

  const wsStore = useWsStore();
  // import { DFWebSocket } from '@/utils/websocket';
  // import { useUserStoreWidthOut } from '@render/store/modules/user';

  const props = withDefaults(defineProps<Props>(), {
    machine: () => ref(null),
    shiftData: () => ({}),
    distributeInfo: () => ref(null),
    isElectron: () => ref(false),
  });

  let adjustingOptions: any = {};

  const { getDictDataListFn, language, message, t } = useMixins();

  interface Props {
    machine: any;
    shiftData: any;
    distributeInfo: any;
    isElectron: any;
  }

  // const userStore = useUserStoreWidthOut();

  const loading = ref(false);

  const topViewRef = ref(null);

  const bottomViewRef = ref(null);

  const printingTemplateRef = ref(null);

  const drawerTemplateRef: any = ref(null);

  const drawerTemplateModalRef: any = ref(null);

  const alarmDialog: any = ref(null);

  const dfPageListRef = ref(null);

  const adjustmentOrderDialogRef = ref(null);

  const unitOptionsDialogRef = ref(null);

  const centerViewRef = ref(null);

  const checkOrderInfoRef = ref(null);

  const isAdjuest = ref(null);

  const isAutoSuccessWork = ref(null);

  const canAutoSuccessWork = ref(true);

  const labelPrintTop = ref(null);

  const isOpenUnitOptions = ref(null);

  const isAutoChangeOrder = ref(null);

  const zeroNoSuccessWork = ref(null);

  const distributionByOrderCode = ref(storage.get('distributionByOrderCode', null));

  const showPage = ref(false);

  const orderList = ref([]);

  const distributionOrder = ref(null);

  const priorityDistributionList = ref([]);

  const normalDistributionList = ref([]);

  const saveByMaterialList = ref([]);

  const parameterUnitList = ref([]);

  const alarmTypeList = ref([]);

  const shiftTimeTypeList = ref([]);

  const imgList = ref([]);

  const plcStore = usePlcWithOut();

  const modbusNewData: any = computed(() => plcStore.newData);

  let btnOptions = null;

  let adjustingSetting = null;

  let checkTime = null;

  let checkNum = 0;

  let productionQuantitySetFunIdVal = null;

  let beforeStartWorkProductionQuantityGetVal = null;

  provide('modbusNewData', modbusNewData);

  const plcClick = inject('plcClick', (_obj) => {});

  provide('provitClickFn', ref(plcClick));

  const chooseItem = ref(null);

  provide('chooseItem', chooseItem);

  const corrugatedTypeNameList = ref([]);

  provide('lengOptionsList', corrugatedTypeNameList);

  const interfaceImageList = ref([]);

  provide('interfaceImageList', interfaceImageList);

  const proSearch = ref('');

  function setProSearchValFn(val) {
    proSearch.value = val === undefined || val === null ? '' : val;

    loadOrderFn();
  }

  function getCurrentTimeRangeTimestamps(data) {
    // 获取当前时间
    let currentDate = new Date();
    let currentHours = currentDate.getHours();
    let currentMinutes = currentDate.getMinutes();
    let currentTotalMinutes = currentHours * 60 + currentMinutes;

    // 遍历数据中的时间段
    for (let i = 0; i < data.length; i++) {
      let extend1 = parseTime(data[i].extend1);
      let extend2 = parseTime(data[i].extend2);

      let extend1TotalMinutes = extend1.hours * 60 + extend1.minutes;
      let extend2TotalMinutes = extend2.hours * 60 + extend2.minutes;

      // 检查时间段是否跨越午夜
      if (extend1TotalMinutes <= extend2TotalMinutes) {
        // 时间段未跨越午夜的情况
        if (
          currentTotalMinutes >= extend1TotalMinutes &&
          currentTotalMinutes < extend2TotalMinutes
        ) {
          return {
            timestamp1: setTimeOnDate(currentDate, extend1.hours, extend1.minutes),
            timestamp2: setTimeOnDate(currentDate, extend2.hours, extend2.minutes),
          };
        }
      } else {
        // 时间段跨越午夜的情况
        if (
          currentTotalMinutes >= extend1TotalMinutes ||
          currentTotalMinutes < extend2TotalMinutes + (24 * 60 - extend1TotalMinutes)
        ) {
          let timestamp1, timestamp2;
          if (currentTotalMinutes < extend2TotalMinutes + (24 * 60 - extend1TotalMinutes)) {
            // 当前时间在第二天的时间段内
            timestamp1 = setTimeOnDate(currentDate, extend2.hours, extend2.minutes);
            // 将日期向后推一天
            let previousDate = new Date(currentDate);
            previousDate.setDate(previousDate.getDate() + 1);
            timestamp2 = setTimeOnDate(previousDate, extend1.hours, extend1.minutes);
          } else {
            // 当前时间在第一天的时间段内
            timestamp1 = setTimeOnDate(currentDate, extend1.hours, extend1.minutes);
            timestamp2 = setTimeOnDate(currentDate, extend2.hours, extend2.minutes);
          }
          return { timestamp1, timestamp2 };
        }
      }
    }

    return null; // 如果当前时间不在任何时间段内
  }

  // 设置指定小时和分钟的时间
  function setTimeOnDate(date, hours, minutes) {
    let newDate = new Date(date);
    newDate.setHours(hours, minutes, 0, 0);
    return newDate;
  }

  // 解析时间字符串，返回小时和分钟
  function parseTime(timeStr) {
    let parts = timeStr.split(':');
    return {
      hours: parseInt(parts[0], 10),
      minutes: parseInt(parts[1], 10),
    };
  }

  let time: any = null;

  const productionTime = ref(null);

  const shutdownTime = ref(null);

  const shiftTimeRes: any = ref(null);

  const machineStatusBoolVal: any = ref(null);

  function clearShiftTimeFn() {
    if (time) {
      clearTimeout(time);

      time = null;
    }
  }

  function updateShutdownTimeFn(machineStatus) {
    if (machineStatus === null) {
      return;
    }

    machineStatusBoolVal.value = machineStatus;
  }

  function updateProductionTimeFn() {
    clearShiftTimeFn();

    productionTime.value = productionTime.value + 1000;

    if (machineStatusBoolVal.value === false) {
      shutdownTime.value = shutdownTime.value + 1000;
    }

    time = setTimeout(() => {
      bottomViewRef.value?.setActionRefTableData([
        {
          ...toRaw(shiftTimeRes.value),
          id: uuidv4(),
          thisShift: t('productionCenter.table.thisShift'),
          productionTime: msToTime(productionTime.value),
          shutdownTime: msToTime(shutdownTime.value),
        },
      ]);

      updateProductionTimeFn();
    }, 1000);
  }

  function updateShiftTimeFn() {
    const { shutdownTime: sShutdownTime, productionTime: sProductionTime } = shiftTimeRes.value;

    productionTime.value = sProductionTime;

    shutdownTime.value = sShutdownTime;

    if (chooseItem.value?.orderStatusCode === '30') {
      updateProductionTimeFn();
    }
  }

  let isFirstLoadOrder = true;

  async function loadOrderFn(fn?) {
    if (props.machine && props.machine.machineCode) {
      if (bottomViewRef.value) {
        bottomViewRef.value.setTableLoadingFn(true);
      }

      const timestamps = getCurrentTimeRangeTimestamps(shiftTimeTypeList.value);

      const list = [
        getOrderByMachineCode({
          machineCode: props.machine.machineCode,
          proSearch: proSearch.value,
        }),
      ];

      if (timestamps) {
        list.push(
          getStatisticsByShiftTime({
            machineCode: props.machine.machineCode,
            startTime: new Date(timestamps.timestamp1).getTime(),
            endTime: new Date(timestamps.timestamp2).getTime(),
          })
        );
      }

      const resList = await Promise.all(list);

      const [res] = resList;

      const { data } = res;

      if (data && data.length) {
        res.data = data
          .sort((a, _b) => {
            if (a.orderStatusCode === '30') return -1;

            return 0;
          })
          .map((item, key) => {
            const {
              scheduledEndTime,
              scheduledStartTime,
              materialLength,
              materialWidth,
              materialHeight,
              paperLength,
              paperWidth,
              materialCode,
              version,
            } = item;

            let autoFlag = 0;

            if (isAutoChangeOrder.value === '1') {
              if (key === 0) {
                if (
                  data.length > 1 &&
                  data[key + 1] &&
                  materialCode === data[key + 1].materialCode &&
                  version === data[key + 1].version
                ) {
                  autoFlag = 1;
                }
              } else if (
                data[key - 1] &&
                data[key - 1].autoFlag === 1 &&
                materialCode === data[key - 1].materialCode &&
                version === data[key - 1].version
              ) {
                autoFlag = 1;
              }
            }

            item.autoFlag = autoFlag;

            return {
              ...item,
              autoFlag,
              paperSize: `${paperLength}*${paperWidth}`,
              materialStandards: `${materialLength}*${materialWidth}*${materialHeight}`,
              scheduledEndTime: scheduledEndTime ? dateFn(new Date(scheduledEndTime)) : '-',
              scheduledStartTime: scheduledStartTime ? dateFn(new Date(scheduledStartTime)) : '-',
            };
          });

        orderList.value = res.data;

        chooseItem.value = res.data[0];

        if (centerViewRef && centerViewRef.value && centerViewRef.value.updateFn) {
          centerViewRef.value.getShutdownListByOrderCodeFn(res.data[0]);
        }

        if (isFirstLoadOrder) {
          nextTick(() => {
            centerViewRef.value.updateMachineStatusFn(true);
          });

          isFirstLoadOrder = false;
        }

        await getDistributeParameterFn();
      } else {
        chooseItem.value = null;

        orderList.value = [];

        distributionByOrderCode.value = null;

        storage.set('distributionByOrderCode', null);
      }

      if (timestamps) {
        clearShiftTimeFn();

        const res2 = resList[1];

        if (bottomViewRef.value && res2?.data && res2?.data.length) {
          const { shutdownTime, productionTime } = res2.data[0];

          shiftTimeRes.value = res2.data[0];

          res2.data[0] = {
            ...res2.data[0],
            id: uuidv4(),
            thisShift: t('productionCenter.table.thisShift'),
            shutdownTime: msToTime(shutdownTime),
            productionTime: msToTime(productionTime),
          };

          bottomViewRef.value.setActionRefTableData(res2.data);

          updateShiftTimeFn();

          // setTimeout(() => {
          //   res2.data[0] = {
          //     ...res2.data[0],
          //     shutdownTime: res2.data[0].shutdownTime + 1,
          //     id: uuidv4(),
          //     thisShift: t('productionCenter.table.thisShift'),
          //   };

          //   console.log(res2.data[0]);

          //   bottomViewRef.value.setActionRefTableData(JSON.parse(JSON.stringify(res2.data)));
          // }, 5000);
        }
      }

      nextTick(() => {
        if (topViewRef && topViewRef.value && topViewRef.value.setValFn) {
          topViewRef.value.setValFn();
        }

        if (bottomViewRef.value) {
          bottomViewRef.value.setCrossActionRefTableData(res.data);

          bottomViewRef.value.setTableLoadingFn(false);

          // bottomViewRef.value.tableLoading.value = false;

          nextTick(() => {
            fn && fn();
          });
        }
      });
    }
  }

  async function updateOrderStatusFn(
    item,
    fn = null,
    newChooseItem = null,
    isDistribution = true,
    isAutoChangeOrderSuccessWork = false
  ) {
    const iChooseItem = newChooseItem || chooseItem.value;

    if (item && iChooseItem) {
      let orderStatusCode = '20';

      switch (item.label) {
        case 'startWork':
          orderStatusCode = '30';
          break;
        case 'stopWork':
          orderStatusCode = '60';
          break;
        case 'successWork':
          orderStatusCode = '40';
          break;

        default:
          break;
      }

      const storageReportNum = topViewRef.value.getStorageReportNumFn();

      let reportNum = topViewRef.value.getValNumFn('productionGet');

      if (
        isAutoChangeOrder.value !== '1' &&
        isAutoSuccessWork.value !== '1' &&
        zeroNoSuccessWork.value === '1' &&
        orderStatusCode === '40'
      ) {
        if (reportNum === 0) {
          message.error(t('productionCenter.tips.zeroNoSuccessWork'));

          fn && fn();

          return;
        }
      }

      reportNum = reportNum - storageReportNum;

      const badNum = topViewRef.value.getValNumFn('badNum');

      if (
        isAutoChangeOrder.value === '1' &&
        iChooseItem.autoFlag === 1 &&
        isAutoChangeOrderSuccessWork
      ) {
        if (reportNum + iChooseItem.producedNum > iChooseItem.orderNum) {
          reportNum = iChooseItem.orderNum - iChooseItem.producedNum;
        }

        topViewRef.value.setStorageReportNumFn(storageReportNum + reportNum);
      }

      const waterConsumption = modbusNewData.value['waterConsumption'] || 0;

      const electricityConsumption = modbusNewData.value['electricityConsumption'] || 0;

      await updateOrder({
        orderStatusCode,
        id: iChooseItem.id,
        ...(orderStatusCode === '30' ? {} : { reportNum, badNum }),
        electricityConsumption,
        waterConsumption,
        ...toRaw(props.shiftData),
      });

      message.success(t('common.tipMsg.isSucc'));

      if (orderStatusCode === '30') {
        distributionByOrderCode.value = null;

        storage.set('distributionByOrderCode', null);

        topViewRef.value.setValNumFn('badNum', 0);

        if (isDistribution) {
          topViewRef.value.setStorageReportNumFn(0);

          if (isOpenUnitOptions.value === '1' && props.distributeInfo) {
            if (
              unitOptionsDialogRef &&
              unitOptionsDialogRef.value &&
              unitOptionsDialogRef.value.openModalFn
            ) {
              unitOptionsDialogRef.value.openModalFn();
            }
          } else {
            distributionFn();
          }
        } else {
          distributionByOrderCode.value = iChooseItem.orderCode;

          storage.set('distributionByOrderCode', iChooseItem.orderCode);
        }
      } else {
        saveParameterByMaterialVersionFn();

        clearCheckTimeFn();
      }

      fn && fn();
    }
  }

  async function autoChangeOrderFn(newChooseItem, fn) {
    const reportChooseItem = toRaw(chooseItem.value);

    chooseItem.value = newChooseItem;

    // await getDistributeParameterFn();

    // distributionFn(null, true);

    await updateOrderStatusFn(
      {
        label: 'successWork',
      },
      null,
      reportChooseItem,
      false,
      true
    );

    await updateOrderStatusFn(
      {
        label: 'startWork',
      },
      null,
      newChooseItem,
      false
    );

    await loadOrderFn(fn);
  }

  function clearCheckTimeFn() {
    if (checkTime) {
      clearInterval(checkTime);

      checkTime = null;

      checkNum = 0;
    }
  }

  async function distributionFn(printUnitObj = null, autoChangeOrder = false) {
    clearCheckTimeFn();

    if (
      priorityDistributionList &&
      priorityDistributionList.value &&
      priorityDistributionList.value.length
    ) {
      const { productionQuantitySet, productionQuantityGet } = modbusNewData.value;

      beforeStartWorkProductionQuantityGetVal = Number(
        modbusNewData.value['productionQuantityGet']
      );

      // let productionQuantityGetFunIdVal = null;

      for (const item of priorityDistributionList.value) {
        const obj = toRaw(item);

        const { funId } = obj;

        if (printUnitObj) {
          if (funId.includes('Unit')) {
            const key = Number(funId.slice(0, 1));

            if (!isNaN(key) && printUnitObj[key]) {
              obj.funId = `${printUnitObj[key]}${funId.slice(1, funId.length)}`;
            }
          }
        }

        if (autoChangeOrder && !item.isDistributeByAutoChangeOrder) {
          continue;
        }

        if (funId === 'productionQuantitySet') {
          productionQuantitySetFunIdVal = obj['value'];
        }

        plcClick(obj);
      }

      const productionQuantitySetVal = Number(productionQuantitySet);

      const productionQuantityGetVal = Number(productionQuantityGet);

      if (
        !isNaN(productionQuantitySetVal) &&
        !isNaN(productionQuantityGetVal) &&
        productionQuantitySetFunIdVal !== null &&
        !isNaN(beforeStartWorkProductionQuantityGetVal)
      ) {
        canAutoSuccessWork.value = false;

        checkTime = setInterval(() => {
          if (
            productionQuantitySetFunIdVal ===
              Number(modbusNewData.value['productionQuantitySet']) &&
            (Number(modbusNewData.value['productionQuantityGet']) <
              beforeStartWorkProductionQuantityGetVal ||
              beforeStartWorkProductionQuantityGetVal === 0 ||
              Number(modbusNewData.value['productionQuantityGet']) === 0)
          ) {
            canAutoSuccessWork.value = true;

            clearCheckTimeFn();

            console.log('可以自动完工');
          }

          checkNum++;

          if (checkNum >= 3000) {
            canAutoSuccessWork.value = true;

            clearCheckTimeFn();

            console.log('超时，可以自动完工');
          }
        }, 1);
      }
    }

    if (
      normalDistributionList &&
      normalDistributionList.value &&
      normalDistributionList.value.length
    ) {
      for (const item of normalDistributionList.value) {
        const obj = toRaw(item);

        if (printUnitObj) {
          const { funId } = obj;

          if (funId.includes('Unit')) {
            const key = Number(funId.slice(0, 1));

            if (!isNaN(key) && printUnitObj[key]) {
              obj.funId = `${printUnitObj[key]}${funId.slice(1, funId.length)}`;
            }
          }
        }

        if (item.time) {
          clearTimeout(item.time);

          item.time = null;
        }

        if (autoChangeOrder && !item.isDistributeByAutoChangeOrder) {
          continue;
        }

        if (item.delayTime) {
          item.time = setTimeout(() => {
            plcClick(obj);

            clearTimeout(item.time);

            item.time = null;
          }, item.delayTime);
        } else {
          plcClick(obj);
        }
      }
    }

    nextTick(() => {
      distributionByOrderCode.value = chooseItem.value.orderCode;

      storage.set('distributionByOrderCode', chooseItem.value.orderCode);
    });
  }

  async function updateAdjuestOrderFn(fn) {
    if (
      chooseItem &&
      chooseItem.value &&
      topViewRef &&
      topViewRef.value &&
      topViewRef.value.getValNumFn
    ) {
      const adjuestNum = topViewRef.value.getValNumFn('adjuestNum');

      await updateAdjuestOrder({ id: chooseItem.value.id, adjuestNum });

      saveParameterByMaterialVersionFn();

      fn && fn();
    }
  }

  // let socket = null;

  // const createSocketFn = () => {
  //   socket = new DFWebSocket({
  //     url: `ws://localhost:7002/ws-api/?token=${userStore.getToken}&EIO=4&transport=websocket`,
  //     callBack: (message: Record<any, string>) => {
  //       console.log(message);
  //     },
  //   });
  // };

  function loadWsOrderFn(fn?) {
    if (props.machine && props.machine.machineCode) {
      nextTick(() => {
        if (bottomViewRef.value) {
          const { machineCodeObj } = wsStore;

          const wsOrderList = machineCodeObj[props.machine.machineCode]?.orderList || [];

          if (JSON.stringify(wsOrderList) !== JSON.stringify(unref(orderList.value))) {
            bottomViewRef.value.setTableLoadingFn(true);

            orderList.value = wsOrderList;

            chooseItem.value = wsOrderList && wsOrderList.length ? wsOrderList[0] : null;

            nextTick(() => {
              if (bottomViewRef.value) {
                bottomViewRef.value.setCrossActionRefTableData(wsOrderList);

                bottomViewRef.value.setTableLoadingFn(false);

                // bottomViewRef.value.tableLoading.value = false;

                nextTick(() => {
                  fn && fn();
                });
              }
            });
          }
        }
      });
    }
  }

  async function changeChooseItemFn(row) {
    if (row) {
      if (isAutoChangeOrder.value === '1' && orderList.value.length > 1) {
        const data = orderList.value;

        const { materialCode, version, orderCode } = row;

        orderList.value = data.map((item, key) => {
          let autoFlag = 0;

          if (orderCode !== item.orderCode || key === 0) {
            if (key === 0) {
              if (
                data.length > 1 &&
                data[key + 1] &&
                materialCode === data[key + 1].materialCode &&
                version === data[key + 1].version
              ) {
                autoFlag = 1;
              }
            } else if (
              data[key - 1] &&
              data[key - 1].autoFlag === 1 &&
              item.materialCode === data[key - 1].materialCode &&
              item.version === data[key - 1].version
            ) {
              autoFlag = 1;
            }
          } else {
            if (materialCode === data[0].materialCode && version === data[0].version) {
              autoFlag = 1;
            }
          }

          item.autoFlag = autoFlag;

          return item;
        });
      }

      chooseItem.value = row;

      await getDistributeParameterFn();
    }
  }

  async function computedDistributeParameterFn(row, fn?) {
    let returnData = {
      priorityDistributionList: [],
      normalDistributionList: [],
      saveByMaterialList: [],
    };

    if (row && props.distributeInfo) {
      const { materialCode, version } = row;

      const { distributeList } = props.distributeInfo;

      if (distributeList && distributeList.length) {
        const res = await getParameterByMaterialVersion({
          materialCode,
          version,
          machineCode: props.machine.machineCode,
        });

        const parameterObj = {};

        if (res.data && res.data.length) {
          for (const item of res.data) {
            const { parameterCode, value } = item;

            parameterObj[parameterCode] = value;
          }
        }

        const {
          priorityDistributionList: pList,
          normalDistributionList: nList,
          saveByMaterialList: sList,
        } = handleDistributeFn(
          distributeList,
          chooseItem.value,
          parameterObj,
          isAutoChangeOrder.value,
          orderList.value
        );

        console.log('优先下发', pList);

        console.log('正常下发', nList);

        console.log('保存参数', sList);

        returnData = {
          priorityDistributionList: pList,
          normalDistributionList: nList,
          saveByMaterialList: sList,
        };
      }
    }

    fn && fn(returnData);

    return returnData;
  }

  async function getDistributeParameterFn() {
    if (chooseItem && chooseItem.value && props.distributeInfo) {
      const { orderCode } = chooseItem.value;

      if (orderCode === distributionOrder.value) {
        return;
      }

      const {
        priorityDistributionList: pList,
        normalDistributionList: nList,
        saveByMaterialList: sList,
      } = await computedDistributeParameterFn(chooseItem.value);

      priorityDistributionList.value = pList;

      normalDistributionList.value = nList;

      saveByMaterialList.value = sList;

      distributionOrder.value = orderCode;

      if (isOpenUnitOptions.value === '1') {
        getParameterUnitByMaterialVersionFn();
      }
    }
  }

  async function getParameterUnitListFn(row = chooseItem.value, fn?) {
    let dataList = [];

    if (row) {
      const { materialCode, version } = row;

      const res = await getParameterUnitByMaterialVersion({
        materialCode,
        version,
        machineCode: props.machine.machineCode,
      });

      dataList = res.data || [];
    }

    fn && fn(dataList);

    return dataList;
  }

  async function getParameterUnitByMaterialVersionFn() {
    parameterUnitList.value = await getParameterUnitListFn(chooseItem.value);
  }

  async function saveParameterByMaterialVersionFn() {
    if (
      chooseItem &&
      chooseItem.value &&
      saveByMaterialList &&
      saveByMaterialList.value &&
      saveByMaterialList.value.length
    ) {
      const { materialCode, version } = chooseItem.value;

      const { machineCode } = props.machine;

      const list = [];

      for (const item of saveByMaterialList.value) {
        const { saveParameterCode, parameterCode } = item;

        const value = Number(modbusNewData.value[saveParameterCode || parameterCode]);

        if (!isNaN(value)) {
          list.push({
            parameterCode,
            materialCode,
            version,
            machineCode,
            value: value.toString(),
          });
        }
      }

      if (list && list.length) {
        await saveParameterByMaterialVersion({
          materialCode,
          version,
          machineCode,
          list,
        });
      }
    }
  }

  async function getDefaultTemplateFn() {
    try {
      const res = await defaultPrintTemplate();

      const { tempInfo = null } = res.data || {};

      if (tempInfo) {
        const val = JSON.parse(tempInfo);

        if (
          val &&
          printingTemplateRef &&
          printingTemplateRef.value &&
          printingTemplateRef.value.setPrintHtmlFn
        ) {
          const {
            tempTitleZh = null,
            tempTitleEn = null,
            descriptiveInformationList = null,
            tableInformationList = null,
          } = val;

          const title = language.value === 'zh' ? tempTitleZh : tempTitleEn;

          const headTable: any = [];

          const table: any = [];

          if (descriptiveInformationList && descriptiveInformationList.length) {
            for (const item of descriptiveInformationList) {
              const {
                columnName = null,
                columnDetailZh = null,
                columnDetailEn = null,
                customNameZh = null,
                customNameEn = null,
                customValue = null,
              } = item;

              headTable.push({
                name:
                  language.value === 'zh'
                    ? customNameZh || columnDetailZh
                    : customNameEn || columnDetailEn,
                prop: customValue ? null : columnName,
                value: customValue || '-',
              });
            }
          }

          if (tableInformationList && tableInformationList.length) {
            for (const item of tableInformationList) {
              const {
                columnName1 = null,
                columnDetailZh1 = null,
                columnDetailEn1 = null,
                customNameZh1 = null,
                customNameEn1 = null,
                customValue1 = null,
                columnName2 = null,
                columnDetailZh2 = null,
                columnDetailEn2 = null,
                customNameZh2 = null,
                customNameEn2 = null,
                customValue2 = null,
              } = item;

              table.push({
                name:
                  language.value === 'zh'
                    ? customNameZh1 || columnDetailZh1
                    : customNameEn1 || columnDetailEn1,
                prop: customValue1 ? null : columnName1,
                value: customValue1 || '-',
                name2:
                  language.value === 'zh'
                    ? customNameZh2 || columnDetailZh2
                    : customNameEn2 || columnDetailEn2,
                prop2: customValue2 ? null : columnName2,
                value2: customValue2 || '-',
              });
            }
          }

          printingTemplateRef.value.setPrintHtmlFn({
            title,
            headTable,
            table,
          });
        }
      }
    } catch (e) {
      console.log(e);
    }
  }

  async function getListConfigFn(configCodeList: any, dataList) {
    const { data } = await listInfoParamConfigList(configCodeList);

    if (data && data.length) {
      for (let i = 0; i < data.length; i++) {
        dataList[i].value = data[i]?.configValue || null;
      }
    }
  }

  function wsSendLoadOrderFn() {
    if (props.isElectron) {
      loadOrderFn();
    } else {
      loadWsOrderFn();
    }
  }

  async function infoAdjustmentFn() {
    const { data } = await infoMachineAdjustment({ machineCode: props.machine.machineCode });

    if (data && data.machineAdjustmentJson) {
      const { btn, adjustingSetting: dAdjustingSetting } = data.machineAdjustmentJson;

      if (btn) {
        btnOptions = btn;
      }

      adjustingOptions = data.machineAdjustmentJson;

      adjustingSetting = dAdjustingSetting;
    }
  }

  async function initDictData() {
    loading.value = true;

    const res = await Promise.all([
      getDictDataListFn('corrugated_type'),
      listInterfaceImage(),
      getDictDataListFn('alarm_type'),
      getDictDataListFn('shift_time_type'),
      getListConfigFn(
        [
          'isAdjuest',
          'isAutoSuccessWork',
          'labelPrintTop',
          'isOpenUnitOptions',
          'isAutoChangeOrder',
          'zeroNoSuccessWork',
        ],
        [
          isAdjuest,
          isAutoSuccessWork,
          labelPrintTop,
          isOpenUnitOptions,
          isAutoChangeOrder,
          zeroNoSuccessWork,
        ]
      ),
      getDefaultTemplateFn(),
      infoAdjustmentFn(),
    ]);

    const [list1, list2, list3, list4] = res;

    corrugatedTypeNameList.value = list1;

    interfaceImageList.value = list2?.data || [];

    alarmTypeList.value = list3;

    shiftTimeTypeList.value = list4;

    nextTick(() => {
      loading.value = false;

      nextTick(async () => {
        if (props.isElectron) {
          await loadOrderFn();

          nextTick(() => {
            if (chooseItem.value && chooseItem.value.orderStatusCode === '30') {
              if (
                !distributionByOrderCode.value ||
                distributionByOrderCode.value !== chooseItem.value.orderCode
              ) {
                distributionByOrderCode.value = chooseItem.value.orderCode;

                storage.set('distributionByOrderCode', chooseItem.value.orderCode);
              }
            } else {
              distributionByOrderCode.value = null;

              storage.set('distributionByOrderCode', null);
            }

            // createSocketFn();
          });
        } else {
          loadWsOrderFn();
        }

        nextTick(() => {
          wsStore.client.subscribe(LOAD_ORDER_LIST, wsSendLoadOrderFn);
        });
      });
    });
  }

  initDictData();

  function openDrawerTemplateModalFn(data, id: any = null, scrollId: any = null) {
    if (
      data &&
      drawerTemplateModalRef &&
      drawerTemplateModalRef.value &&
      drawerTemplateModalRef.value.openModalFn
    )
      drawerTemplateModalRef.value.openModalFn(data, id, scrollId);
  }

  provide('openDrawerTemplateModalFn', openDrawerTemplateModalFn);

  function openDrawerFn(type, id: any = null, scrollId: any = null) {
    const data = adjustingOptions[type];

    console.log(adjustingOptions);

    console.log(type);

    console.log(data);

    if (
      data &&
      !data.notOpen &&
      drawerTemplateRef &&
      drawerTemplateRef.value &&
      drawerTemplateRef.value.open
    ) {
      drawerTemplateRef.value.open(data, id, scrollId);
    }
  }

  provide('openDrawerFn', openDrawerFn);

  const pageOptions = {
    modalFormDialog: {
      formSchemas: [
        {
          label: 'configName',
          editDialogDisabled: true,
          required: true,
        },
        {
          label: 'configCode',
          editDialogDisabled: true,
          required: true,
        },
        {
          label: 'configValue',
        },
        {
          label: 'remark',
          common: true,
          type: 'textarea',
        },
      ],
      submitDataFn: () => {},
    },
  };

  function openPageListDialogFn(modalFormDialog, title, data?) {
    if (modalFormDialog) {
      pageOptions.modalFormDialog = modalFormDialog;

      showPage.value = false;

      nextTick(() => {
        showPage.value = true;

        nextTick(() => {
          dfPageListRef.value.openModalFn(null, null, title);

          if (data) {
            nextTick(() => {
              dfPageListRef.value.setFieldsValueFn(data);
            });
          }
        });
      });
    }
  }

  function closePageListDialogFn(isLoadOrder = false, machineCode = null) {
    dfPageListRef.value.closeModalFn();

    if (isLoadOrder) {
      loadOrderFn();

      wsStore.client.emit('sendMachineCodeLoadOrder', {
        machineCode,
      });
    }

    isLoadOrder &&
      nextTick(() => {
        showPage.value = false;
      });
  }

  function openAdjustmentOrderDialogFn() {
    if (adjustmentOrderDialogRef.value && adjustmentOrderDialogRef.value.openModalFn) {
      adjustmentOrderDialogRef.value.openModalFn();
    }
  }

  function setImgListFn(list) {
    imgList.value = list;
  }

  function setCenterViewValFn() {
    if (centerViewRef && centerViewRef.value && centerViewRef.value.updateFn) {
      centerViewRef.value.updateFn();
    }
  }

  function checkOrderInfoFn(row) {
    if (checkOrderInfoRef && checkOrderInfoRef.value && checkOrderInfoRef.value.openFn) {
      checkOrderInfoRef.value.openFn(row);
    }
  }

  // const alarmListLength = computed(() => projectStore.alarmList.length);
  let newAlarmList: any = [];

  const { alarmList } = toRefs(projectStore);

  if (alarmList.value.length) {
    newAlarmList = alarmList;

    nextTick(() => {
      alarmDialog.value?.openModalFn();
    });
  }

  watch(
    alarmList,
    (val) => {
      if (JSON.stringify(newAlarmList) !== JSON.stringify(val)) {
        if (val.length) {
          alarmDialog.value?.openModalFn();
        } else {
          alarmDialog.value?.closeModalFn();
        }

        newAlarmList = val;
      }
    },
    {
      deep: true,
      immediate: true,
    }
  );

  onBeforeMount(() => {
    clearCheckTimeFn();

    clearShiftTimeFn();

    wsStore.client.unsubscribe(LOAD_ORDER_LIST, wsSendLoadOrderFn);
  });
</script>

<style lang="less" scoped>
  .no-drop {
    cursor: no-drop;
  }
  .productionCenter-home {
    min-height: 100%;

    &.disable-click {
      pointer-events: none;
    }

    :deep(.bottom-view),
    :deep(.center-view-bottom) {
      padding: 16px 16px 0;
      .n-button {
        min-width: 136px;
        height: 48px;
        font-size: 20px;
        margin-right: 16px;
        margin-bottom: 16px;
      }
    }
  }
</style>
